// 这里存放 常用的工具类

import {
  promisifyAll,
  promisify
} from 'miniprogram-api-promise';
import { HE_WEATHER_KEY, TENCENT_MAP_KEY } from './config';
var CryptoJS = require("crypto-js");
export let wxp = {};
promisifyAll(wx, wxp)


// TODO XIAOSHENG 2020年8月30日 21:52:30

// 跳转页面方法，减少书写：传值为页面路径
export function tz(e) {

  if (e) wx.navigateTo({
    url: e
  })
  else toast('跳转失败')
}

// 短震动
export function vbs(e) {
  let {platform} = wx.getSystemInfoSync();
  if(platform === 'devtools'){return};//开发者工具中不震动
  wx.vibrateShort({
    success: (res) => {},
  })
}

/**
 * 显示Toast提示
 * title     内容       默认 错误
 * icon      图标       默认 none
 * duration  显示时长ms  默认 2000
 */
export function toast(title='错误',icon='none',duration=2000) {
  wx.showToast({ title ,duration,icon})
}






/**
 * 将秒数转换成  mm:ss 格式
 * @param {*} sec  要转换的描述 整数
 */
export function formateSeconds(sec) {
  let secondTime = Math.round(sec) //将传入的秒的值转化为Number
  let min = 0 // 初始化分
  let h = 0 // 初始化小时
  let result = ''
  if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
    min = parseInt(secondTime / 60) //获取分钟，除以60取整数，得到整数分钟
    secondTime = parseInt(secondTime % 60) //获取秒数，秒数取佘，得到整数秒数
    if (min > 60) { //如果分钟大于60，将分钟转换成小时
      h = parseInt(min / 60) //获取小时，获取分钟除以60，得到整数小时
      min = parseInt(min % 60) //获取小时后取佘的分，获取分钟除以60取佘的分
    }
  }
  result = sec > 60 * 60 * 60 ? `${h.toString().padStart(2,'0')}:` : `` + `${min.toString().padStart(2,'0')}:${secondTime.toString().padStart(2,'0')}`
  return result
}


// 日期格式化
export function DateFormat(date, fmt) { //author: meizz
  // this = 
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds(), //毫秒
    "w": `周${["日","一","二","三","四","五","六"][date.getDay()]}`
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
};



/**
 * 获取音频时长
 * @param {*} innerAudioContext //InnerAudioContext对象
 */
export async function getAudioDuration(innerAudioContext) {
  return new Promise((resolve, reject) => {
    innerAudioContext.onCanplay(() => {
      innerAudioContext.duration;
      setTimeout(() => {
        resolve(innerAudioContext.duration)
      }, 500)
    })

  })
}
/**
 * 获取文件后缀名
 * @param {*} fileName 
 */
export function getSiffix(fileName) {
  return /\.[^\.]+$/.exec(fileName);
}



/**
 * 语音转文字
 * @param {*} url      要识别的音频文件url
 * @param {*} fileId   云存储文件id  用于生成UsrAudioKey，为空的话则根据时间戳生成[选填] 
 */
export async function speechToText({
  url,
  fileId
}) {
  let UsrAudioKey = fileId ? `STT-${fileID}` : `SST-${new Date().getTime()}`
  let  data = await wx.serviceMarket.invokeService({
    service: 'wxa8386175898e12c9',
    api: 'SentenceASR',
    data: {
      Action: 'SentenceRecognitionWX',
      EngSerViceType: '16k_zh', //引擎模型类型 16k中文普通话,
      VoiceFormat: 'mp3', //要识别的音频格式
      UsrAudioKey, //任务唯一标识用于查找识别结果
      Url: url
    }
  });
  let result = data.data.Response.Result
  return result;
}

/**
 * 图像识别
 * 文档地址 https://developers.weixin.qq.com/community/servicemarket/detail/000ce4cec24ca026d37900ed551415
 * @param {*} img_url 
 * @param {*} array 是否返回数组
 * @returns String  返回图像识别结果
 */
export async function discernORC(img_url, array) {
  let {
    data: {
      ocr_comm_res: {
        items
      }
    }
  } = await wx.serviceMarket.invokeService({
    service: 'wx79ac3de8be320b71', // '固定为服务商OCR的appid，非小程序appid',
    api: 'OcrAllInOne',
    data: {
      img_url, //tempFilePaths,
      data_type: 3, // 1.二进制 2.base64 3.图片URL
      ocr_type: 8, // 1.身份证 2.银行卡 3.行驶证 4.驾驶证 7.营业执照 8.通用OCR
    }
  })
  if (array) {
    return items.map(item => item.text)
  } else {
    return items.reduce((c, p) => `${c}${p}`, "")
  }
}

/**
 * 字符串分词
 * 传入字符串 返回分词后的数组
 * @param {String} text       转换文本
 * @param {Function} process  转换过程回调
 */
export async function bigbang({
  text,
  process
}) {
  let texts = strChunk(text, 10); //因为字符串太长 云函数会超时 所以长度为10 切开分组处理
  let results = await Promise.all(texts.map(async item => { //创建任务
    return await wx.cloud.callFunction({
      name: 'bigbang',
      data: {
        text: item
      }
    });
  }));

  results = results.map(({
    result
  }) => result); //映射
  results = results.reduce((c, p) => {
    return [...c, ...p]
  }, []);
  results = results.map(item => item.w);
  return results;
}
/**
 * 字符串切块
 * 返回切割后的数组
 * @example
 * strChunk("hellonicetomeetyou",3)
 * 返回 ["hel", "lon", "ice", "tom", "eet", "you"]
 * @param {*} str       //要切块的字符串
 * @param {*} size      //切割尺寸
 * @param {*} cacheStr 
 */
export function strChunk(str, size = 1, cacheStr = []) {
  const tmp = [...str]
  if (size <= 0) {
    return cacheStr
  }
  while (tmp.length) {
    cacheStr.push(tmp.splice(0, size).join(""))
  }
  return cacheStr
}
/**
 * 延时 
 * @param {*} ms 毫秒
 */
export async function delay(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve(), ms)
  })
}
export async function getUserInfo() {
  let userData = await wx.cloud.callFunction({
    name: 'user',
    data: {
      _op: 'get',
    }
  })
  return userData.result
}

export async function updateUserInfo(users) {
  let userData = await wx.cloud.callFunction({
    name: 'user',
    data: {
      _op: 'save',
      users,
      authorized: 1
    },
  })
  return userData.result
}
export function getTimeState() {
  let hours = new Date().getHours()
  if (hours >= 0 && hours <= 5) return `凌晨`
  else if (hours > 5 && hours <= 10) return `早上`
  else if (hours > 10 && hours <= 14) return `中午`
  else if (hours > 14 && hours <= 17) return `下午`;
  else if (hours > 17 && hours <= 20) return `傍晚`;
  else if (hours > 20 && hours <= 24) return `晚上`;
};


/**
 * 获取本地信息
 * 返回
 * {
 *   ip, IP地址
 *   location:{ 经纬度
 *      lat, 
 *      lng
 * },
 *   ad_info:{
 *      nation,    国家
 *      province,  省份
 *      city,      城市
 *      district,  余杭区
 *      adcode     邮编
 * }
 * }
 */
export async function getLocationInfo() {
  const key = TENCENT_MAP_KEY 
   let {data:{result}}= await wxp.request({
     url: `https://apis.map.qq.com/ws/location/v1/ip?key=${key}&output=json`,
   });
   return result;
};
export async function getWeather(){
  const  key = HE_WEATHER_KEY;
  let localtionInfo = await getLocationInfo();
  console.log("位置信息获取",localtionInfo)
  const {location,ad_info} =localtionInfo;
  // const location = '120.2985,30.41875'
  let {data:{now}} = await wxp.request({
    url:`https://devapi.heweather.net/v7/weather/now`,
    data:{
      key,
      location:`${location.lng},${location.lat}`
    }
  });

  return {...now,...ad_info};
  console.log("天气获取",now)

};
// 输出英文日期 
export function toEnTimes(date) { 
  return date.toDateString() 
} 
 
export function sleep(t = 1) { 
  /*  停止一段时间,用法： 
   sleep(5).then(()=>{要运行的代码})  
  */ 
  return new Promise((resolve) => setTimeout(resolve, t * 1000)); 
} 
 
 /**
  * 页面返回
  * @param {*} e 
  */
export function back(e) { 
  wx.navigateBack({ 
    delta: e || 1, 
  }) 
}
export function makeSign(){
  var nowDate = new Date(); 
  var dateTime = nowDate.toGMTString();
  //dateTime = "Mon, 19 Mar 2018 12:00:44 GMT"
  var SecretId = 'AKIDaS8XfZFYhSyDBrr2kkV1HGyzoMddFuA8'; // 密钥对的 SecretId
  var SecretKey = 'SecretKey:ua5IEuMWQ5UcT21lEPMaYFfohJfjX5LK'; // 密钥对的 SecretKey
  var source = 'EASY_NOTES'; // 签名水印值，可填写任意值
  var auth = `hmac id=${SecretId}, algorithm=hmac-sha1,headers="x-date source",signature=`;
  // var signStr = "x-date: " + dateTime + "\n" + "source: " + source;
  var signStr = `"x-date:${dateTime} source:${source}"`
  var sign = CryptoJS.HmacSHA1(signStr, SecretKey)
  console.log("sign.toString()",sign.toString())
  sign = CryptoJS.enc.Base64.stringify(sign)
  console.log("CryptoJS.enc.Base64.stringify(sign)",sign)

  sign = `${auth}"${sign}"`
  console.log("生成签名",sign)
  return {dateTime,sign,source};
}



